package com.yun.zf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.common.admin.domain.SysUser;
import com.yun.zf.common.admin.domain.SysUserRole;
import com.yun.zf.system.mapper.SysUserRoleMapper;
import com.yun.zf.system.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    @Override
    public void addUserRole(SysUser user) {
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getUserId());
        // 注册默认是普通用户
        userRole.setRoleId(2L);
        baseMapper.insert(userRole);
    }

    @Override
    public List<SysUserRole> getUserRoleList(SysUser user) {

        QueryWrapper<SysUserRole> queryWrapper =  new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getUserId,user.getUserId());
        List<SysUserRole> userRoleList = baseMapper.selectList(queryWrapper);

        return  userRoleList;
    }

    @Override
    public List<Long> getRoleList(Long userId) {
        QueryWrapper<SysUserRole> queryWrapper =  new QueryWrapper<>();
        queryWrapper.select("role_id") .eq("user_id",userId);
        List<Long> userRoleList = baseMapper.selectObjs(queryWrapper).stream().map(o -> (Long)o).collect(Collectors.toList());

        return  userRoleList;
    }

    @Override
    public List<Long> getRoleId(long userId) {
        QueryWrapper<SysUserRole> queryWrapper =  new QueryWrapper<>();
        queryWrapper.select("role_id") .eq("user_id",userId);
        List<Long> userRoleList = baseMapper.selectObjs(queryWrapper).stream().map(o -> (Long)o).collect(Collectors.toList());

        return  userRoleList;
    }

    /**
     * 根据用户id删除角色信息
     * @param userId
     * @return
     */
    @Override
    public int delRolesByUserId(Long userId) {
        QueryWrapper<SysUserRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.lambda().eq(SysUserRole::getUserId,userId);
        return  baseMapper.delete(roleQueryWrapper);
    }

    /**
     * 用户新增角色
     * @param userId
     * @param role_id
     * @return
     */
    @Override
    public int addRoles(Long userId, Long role_id) {
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId(role_id);
        userRole.setUserId(userId);
        return   baseMapper.insert(userRole);

    }

    /**
     * 批量添加数据
     * @param userRoleList
     * @return
     */
    @Override
    public Boolean batchList(List<SysUserRole> userRoleList) {
      return  this.saveBatch(userRoleList);
    }
}
